package com.feishi.project.move;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: caixq
 * Date: 2019-12-12
 * Time: 下午3:09
 */
public class ThreadTest {
    static int num=100;
    public static void main(String[] args) throws InterruptedException {
        final Object obj = new Object();
        Thread A = new Thread(new Runnable() {
            @Override
            public void run() {
                int sum = 0;
                for(int i=0;i<10;i++){
                    sum+=i;
                }
                try {
                    synchronized (obj){
                        obj.wait();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                System.out.println(sum);
            }
        });
        A.start();
        //睡眠一秒钟，保证线程A已经计算完成，阻塞在wait方法


        for (int i = 0; i < 10; i++) {
            new Thread(() -> {while (reduce(Thread.currentThread().getName())){
                try {
//                    Thread.sleep((long) (Math.random()*1000));

                    synchronized (obj){
                        obj.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }}).start();
        }

        Thread.sleep(1000);
        while (num>0){
            System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            Thread.sleep(1000);
            notifyAll(obj);
        }

    }

    private static void notify(Object obj) {
        synchronized (obj){
            obj.notify();
        }
    }
    private static void notifyAll(Object obj) {
        synchronized (obj){
            obj.notifyAll();
        }
    }

    public static synchronized boolean  reduce(String name){
        if(num==0)return false;
        System.out.println(name+"::"+num--);

        return num>0;
    }



}
